package com.itheima.exception;

import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.Objects;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice // 标识当前类是一个全局异常处理器
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 捕获参数校验异常
     */
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handle(MethodArgumentNotValidException e) {
        return Result.error(Objects.requireNonNullElse(e.getBindingResult().getFieldError(), new FieldError("target", "field", "参数验证错误")).getDefaultMessage());
    }
    /**
     * 捕获业务异常
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("通用异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 捕获SQL异常
     */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error("SQL异常信息：{}", ex.getMessage());
        String message = ex.getMessage();
        if (message.contains("Duplicate entry")){//如果异常消息中包含 "Duplicate entry" 字样
            return Result.error("已存在");
        }else {
            return Result.error("UNKNOWN_ERROR");
        }
    }

    /**
     * 捕获算法异常
     */
    @ExceptionHandler
    public Result exceptionHandler(ArithmeticException ex){
        log.error("计算异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }
}
